<template>
  <div class="admin-info">
    <!-- 搜索表单 -->
    <el-form :inline="true" :model="searchForm" class="demo-form-inline">
      <el-form-item>
        <el-button type="success" @click="handleAdd">新增临时工</el-button>
      </el-form-item>
    </el-form>

    <!-- 临时工信息表格 -->
    <el-table :data="adminInfoList" style="width: 100%" class="admin-table">
      <el-table-column prop="name" label="姓名" width="320"></el-table-column>
      <el-table-column prop="phone" label="电话" width="250"></el-table-column>
      <el-table-column prop="username" label="账号" min-width="220"></el-table-column>
      <el-table-column label="过期时间" min-width="180">
        <template #default="scope">
          {{ scope.row.expireTime ? scope.row.expireTime : '无限期' }}
        </template>
      </el-table-column>
    </el-table>

    <!-- 修改/新增信息对话框 -->
    <el-dialog
      :title="dialogType === 'add' ? '新增临时工' : '修改临时工信息'"
      :visible.sync="dialogVisible"
      width="50%"
      @close="handleDialogClose"
    >
      <el-form
        :model="editForm"
        ref="editFormRef"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="editForm.name"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="editForm.phone"></el-input>
        </el-form-item>

        <el-form-item label="过期时间" prop="expireTime">
          <el-date-picker
            v-model="editForm.expireTime"
            type="date"
            placeholder="选择过期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="账号" prop="username">
          <el-input v-model="editForm.username"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleDialogConfirm">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      adminInfoList: [],
      siteOptions: [],
      dialogVisible: false,
      dialogType: 'edit',
      searchForm: {}, // 新增: 初始化 searchForm
      editForm: {
        name: '',
        phone: '',
        siteId: '',
        expireTime: '',
        username: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        siteId: [
          { required: true, message: '请选择站点', trigger: 'change' }
        ],
        username: [
          { required: true, message: '请输入账号', trigger: 'blur' }
        ]
      }
    };
  },
  methods: {
    fetchAdminsBySiteAndRole() {
      axios.get('/zsd-permission/admin-info/getAdminsByAdminIdAndRole', {
        headers: {
          'token': localStorage.getItem('token')
        }
      }).then(response => {
        if (response.data.msg === "查询成功") {
          this.adminInfoList = response.data.data;
        } else {
          this.$message.error(response.data.msg || '查询失败');
        }
      }).catch(error => {
        console.error('查询失败', error);
        this.$message.error('查询失败');
      });
    },
    handleAdd() {
      this.dialogType = 'add';
      this.editForm = {
        name: '',
        phone: '',
        siteId: '',
        expireTime: '',
        username: ''
      };
      this.dialogVisible = true;
    },
    handleEdit(row) {
      this.dialogType = 'edit';
      this.editForm = {
        name: row.name,
        phone: row.phone,
        siteId: row.siteId,
        expireTime: row.expireTime,
        username: row.username
      };
      this.dialogVisible = true;
    },
    handleDelete(row) {
      this.$confirm('此操作将删除该临时工, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.delete('/zsd-permission/admin-info/deleteAdminInfoById', {
          params: {
            adminId: row.adminId
          },
          headers: {
            'token': localStorage.getItem('token')
          }
        }).then(response => {
          if (response.data.code === 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.fetchAdminsBySiteAndRole();
          } else {
            this.$message.error(response.data.msg || '删除失败');
          }
        }).catch(error => {
          console.error('删除失败', error);
          this.$message.error('删除失败');
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleDialogClose() {
      this.$refs.editFormRef.resetFields();
      this.editForm = {
        name: '',
        phone: '',
        siteId: '',
        expireTime: '',
        username: ''
      };
    },
    submitAdd() {
      this.$refs.editFormRef.validate((valid) => {
        if (valid) {
          const formData = {
            name: this.editForm.name,
            phone: this.editForm.phone,
            siteId: this.editForm.siteId,
            expireTime: this.editForm.expireTime ? this.editForm.expireTime.toISOString().split('T')[0] : null,
            username: this.editForm.username
          };

          axios({
            method: 'post',
            url: '/zsd-permission/admin-info/addNewUser',
            data: formData,
            headers: {
              'Content-Type': 'application/json',
              'token': localStorage.getItem('token')
            }
          }).then(response => {
            if (response.data.code === 200) {
              this.$message.success('添加成功');
              this.dialogVisible = false;
              this.fetchAdminsBySiteAndRole();
            } else {
              this.$message.error(response.data.msg || '添加失败');
            }
          }).catch(error => {
            console.error('添加失败', error);
            this.$message.error('添加失败');
          });
        }
      });
    },
    handleDialogConfirm() {
      if (this.dialogType === 'add') {
        this.submitAdd();
      } else {
        // 修改逻辑
      }
    }
  },
  created() {
    this.fetchAdminsBySiteAndRole();
  }
};
</script>

<style scoped>
.admin-info {
  padding: 20px;
  width: 100%;
  box-sizing: border-box;
}

.admin-table {
  width: 100% !important;
  margin: 20px 0;
}

.dialog-footer {
  text-align: right;
  margin-top: 20px;
}

.el-dialog__body {
  padding: 20px 40px;
}

.el-form-item {
  margin-bottom: 20px;
}

@media screen and (max-width: 768px) {
  .el-dialog {
    width: 90% !important;
  }

  .admin-info {
    padding: 10px;
  }

  .admin-table {
    overflow-x: auto;
  }
}
</style>
